const express = require('express');

const port = 18080;

const server = express();

// 启用用于处理 `application/x-www-form-urlencode` 数据的支持
server.use( express.urlencoded({extended:false}) );
// 启用用于处理 `text/plain` 数据的支持
server.use( express.text() );
// 启用用于处理 `application/json` 据的支持
server.use( express.json() );

const users = [
    { id: 9527 , name: '华安' , gender: '男' , birthdate: '1999-10-20' },
    { id: 8526 , name: '秋香' , gender: '女' , birthdate: '2000-10-20' },
    { id: 1234 , name: '瑞斯邦' , gender: '男' , birthdate: '2001-10-20' },
    { id: 5678 , name: '小姜同志' , gender: '男' , birthdate: '1999-05-20' }
];

// GET `/user/list`
server.get('/user/list',(req,resp)=>{
    resp.json( { status: 'success' , message: '查询成功' , users: users } );
});

// GET `/user/:id`
server.get('/user/:id',(req,resp)=>{
    let { id } = req.params;
    let user = users.find( u => u.id == id );
    if( user ) {
        resp.json( { status: 'success' , message: '查询成功' , user: user } );
        return;
    }
    resp.json( { status: 'fail' , message: '查询失败' , reason: '用户不存在' } );
});

// POST `/user/add`
server.post('/user/add',(req,resp)=>{
    // 解构赋值
    let { name , gender , birthdate } = req.body ;

    let reducer = (prev,curr) => prev < curr.id ? curr.id : prev ;
    let maxId = users.reduce( reducer , 0 );

    let user = {
        id: maxId + 1 ,
        name, // 等同于 name: name
        gender,
        birthdate
    }

    users.push( user );
    resp.json( { status: 'success' , message: '添加成功' } );
});

// DELETE `/user/remove/:id`
server.delete('/user/remove/:id',(req,resp)=>{
    // 用 req.params 可以获得通过 路由路径 传递的参数值
    let { id } = req.params ; // 解构赋值
    let index = users.findIndex( u => u.id == id );
    if( index != -1 ) {
        users.splice( index , 1 );
        resp.json( { status: 'success' , message: '删除成功' } );
        return ;
    }
    resp.json( { status: 'fail' , message: '删除失败' } );
});

// PUT `/user/update`
server.put('/user/update' , (req,resp)=>{
    let { id , name , gender , birthdate } = req.body;
    let user = users.find( u => u.id == id );
    if( user ){
        user.name = name ;
        user.gender = gender ;
        user.birthdate = birthdate ;
        resp.json( { status: 'success' , message: '修改成功' } );
        return;
    }
    resp.json( { status: 'fail' , message: '修改失败' } );
});


server.listen(port,()=> console.log(`正在监听${port}端口`));